package so.wy.servicecenter.businessbed.service.pay;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import so.wy.servicecenter.base.exception.ServiceException;
import so.wy.servicecenter.base.frame.service.AbstractService;
import so.wy.servicecenter.businessbed.dao.enums.StatusPayEnum;
import so.wy.servicecenter.businessbed.dao.enums.TypePayBusinessEnum;
import so.wy.servicecenter.businessbed.dao.rdb.pay.PayDAO;
import so.wy.servicecenter.businessbed.dao.rdb.pay.PayDO;
import so.wy.servicecenter.businessbed.manager.normal.OrderOptNManager;
import so.wy.servicecenter.businessbed.manager.normal.RentUserNManager;

import java.math.BigDecimal;

@Service
@Scope("prototype")
public class PayResultService extends AbstractService {
    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private PayDAO payDAO;

    @Autowired
    private OrderOptNManager orderOptNManager;

    @Autowired
    private RentUserNManager rentUserNManager;

    //支付结果回调
    public void handPayResult(String xmlData) throws ServiceException {
        WxPayOrderNotifyResult notifyResult = null;
        try {
            notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
        } catch (WxPayException e) {
            throw exception("解析异常");
        }

        String payPreSeerial = notifyResult.getOutTradeNo();
        BigDecimal totalFee = new BigDecimal(BaseWxPayResult.fenToYuan(notifyResult.getTotalFee()));

        PayDO payDO = checkPayHistory(payPreSeerial);

        try {
            notifyResult.checkResult(wxPayService, notifyResult.getSignType(), true);

            if (TypePayBusinessEnum.ORDER.getCode().equals(payDO.getBusinessType())) {
                //判断是否是订单支付
                orderOptNManager.handOrderPayResult(true, payDO.getBusinessSign());
            } else if (TypePayBusinessEnum.DEPOSIT.getCode().equals(payDO.getBusinessType())) {
                //判断是否是押金支付
                rentUserNManager.yjPayResult(true, payDO.getRentUserId(), totalFee);
            }

            payDO.setPayStatus(StatusPayEnum.SUCCESS.getCode());
        } catch (WxPayException e) {
            logger.error(JSON.toJSONString(e));

            payDO.setPayStatus(StatusPayEnum.FAIL.getCode());

            throw exception("解析异常");
        } finally {
            payDAO.updateById(payDO);
        }

    }

    //退款结果回调
    public void handRefundResult(String xmlData) throws ServiceException {
        WxPayRefundNotifyResult notifyResult;
        try {
            notifyResult = wxPayService.parseRefundNotifyResult(xmlData);
        } catch (WxPayException e) {
            logger.error(JSON.toJSONString(e));
            throw exception("解析异常");
        }

        String refundNo = notifyResult.getReqInfo().getOutRefundNo();
        PayDO payDO = checkPayHistory(refundNo);
        BigDecimal totalFee = new BigDecimal(BaseWxPayResult.fenToYuan(notifyResult.getReqInfo().getTotalFee()));

        rentUserNManager.yjTqResult(true,payDO.getRentUserId(),totalFee);

        payDO.setPayStatus(StatusPayEnum.SUCCESS.getCode());
        payDAO.updateById(payDO);
    }

    private PayDO checkPayHistory(String paySerial) throws ServiceException {
        PayDO payDO = payDAO.selectOne(new LambdaQueryWrapper<PayDO>().eq(PayDO::getPreOrderSerial, paySerial));
        if (payDO == null) {
            throw exception("支付单号不存在!");
        }

        return payDO;
    }
}
